<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/72X72.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/48X48.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/32X32.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"issacyoung.cn","root":"/","scheme":"Pisces","version":"7.7.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="空指针如何避免对象没有初始化直接使用 赋值时自动拆箱出现空指针为什么需要包装器类型？ 为了让基本类型具有对象的性质，可以让容器 Collection 中使用。  变量赋值自动拆箱出现  方法传参自动拆箱出现 1234567891011121314151617181920212223242526272829public class UnboxingNpe &amp;#123;    private stat">
<meta property="og:type" content="article">
<meta property="og:title" content="一步一步之java常见坑">
<meta property="og:url" content="http://issacyoung.cn/2024/04/21/%E4%B8%80%E6%AD%A5%E4%B8%80%E6%AD%A5%E4%B9%8Bjava%E5%B8%B8%E8%A7%81%E5%9D%91/index.html">
<meta property="og:site_name" content="Young‘s River">
<meta property="og:description" content="空指针如何避免对象没有初始化直接使用 赋值时自动拆箱出现空指针为什么需要包装器类型？ 为了让基本类型具有对象的性质，可以让容器 Collection 中使用。  变量赋值自动拆箱出现  方法传参自动拆箱出现 1234567891011121314151617181920212223242526272829public class UnboxingNpe &amp;#123;    private stat">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-04-21T15:23:26.000Z">
<meta property="article:modified_time" content="2024-04-21T15:24:06.337Z">
<meta property="article:author" content="Issac Young">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://issacyoung.cn/2024/04/21/%E4%B8%80%E6%AD%A5%E4%B8%80%E6%AD%A5%E4%B9%8Bjava%E5%B8%B8%E8%A7%81%E5%9D%91/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>一步一步之java常见坑 | Young‘s River</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="Young‘s River" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Young‘s River</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">一个正能量的程序员，喜欢码字，热爱运动，向往自由</p>
  </div>

  <div class="site-nav-right"></div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/IssacYoung2013" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://issacyoung.cn/2024/04/21/%E4%B8%80%E6%AD%A5%E4%B8%80%E6%AD%A5%E4%B9%8Bjava%E5%B8%B8%E8%A7%81%E5%9D%91/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Issac Young">
      <meta itemprop="description" content="现代生活工作节奏越来越快，需要有时间和空间沉淀积累，将知识点规划成树，记录自己的感悟心得。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Young‘s River">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          一步一步之java常见坑
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2024-04-21 23:23:26 / 修改时间：23:24:06" itemprop="dateCreated datePublished" datetime="2024-04-21T23:23:26+08:00">2024-04-21</time>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>9.2k</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="空指针如何避免"><a href="#空指针如何避免" class="headerlink" title="空指针如何避免"></a>空指针如何避免</h3><p>对象没有初始化直接使用</p>
<h4 id="赋值时自动拆箱出现空指针"><a href="#赋值时自动拆箱出现空指针" class="headerlink" title="赋值时自动拆箱出现空指针"></a>赋值时自动拆箱出现空指针</h4><p>为什么需要包装器类型？</p>
<p>为了让基本类型具有对象的性质，可以让容器 Collection 中使用。</p>
<ul>
<li><p>变量赋值自动拆箱出现</p>
</li>
<li><p>方法传参自动拆箱出现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UnboxingNpe</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> x,<span class="keyword">int</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> x + y;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">compare</span><span class="params">(<span class="keyword">long</span> x, <span class="keyword">long</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> x &gt;= y;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 1. 变量赋值自动拆箱出现的空指针</span></span><br><span class="line">        <span class="comment">// javac UnboxingNpe.java</span></span><br><span class="line">        <span class="comment">// javap -c UnboxingNpe.class 反编译汇编</span></span><br><span class="line">        <span class="comment">// 发现 long count_ 调用了 Long.longValue 方法</span></span><br><span class="line"><span class="comment">//        Long count = null;</span></span><br><span class="line"><span class="comment">//        long count_ = count;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2. 方法传参自动拆箱出现的空指针</span></span><br><span class="line"><span class="comment">//        Integer left = null;</span></span><br><span class="line"><span class="comment">//        Integer right = null;</span></span><br><span class="line"><span class="comment">//        System.out.println(add(left,right));</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3. 用于大小比较的场景</span></span><br><span class="line">        Long left = <span class="number">10L</span>;</span><br><span class="line">        Long right = <span class="keyword">null</span>;</span><br><span class="line">        System.out.println(compare(left,right));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h5 id="建议"><a href="#建议" class="headerlink" title="建议"></a>建议</h5><ul>
<li>基于数据类型优先包装器类型，优先使用基本类型</li>
<li>对于不确定的包装器类型，一定要校验是否为NULL</li>
<li>对于值NULL的包装器类型，赋值为0</li>
</ul>
<h4 id="字符串、数组、集合-N-P-E"><a href="#字符串、数组、集合-N-P-E" class="headerlink" title="字符串、数组、集合 N P E"></a>字符串、数组、集合 N P E</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BasicUsageNpe</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">stringEquals</span><span class="params">(String x, String y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// java 比较字符串不能使用==；遵循常量.equals变量</span></span><br><span class="line">        <span class="keyword">return</span> x.equals(y);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> String name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 1. 字符串使用equal</span></span><br><span class="line"><span class="comment">//        System.out.println(stringEquals("xyz", null));</span></span><br><span class="line"><span class="comment">//        System.out.println(stringEquals(null, "xyz"));</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2. 对象数组 new 出来，但是元素没有初始化</span></span><br><span class="line">        User[] users = <span class="keyword">new</span> User[<span class="number">10</span>];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i != <span class="number">10</span>; ++i) &#123;</span><br><span class="line">            users[i] = <span class="keyword">new</span> User();</span><br><span class="line">            users[i].name = <span class="string">"issac-"</span> + i;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3. List 对象 allAll 传递 null</span></span><br><span class="line">        List&lt;User&gt; userList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        User user = <span class="keyword">null</span>;</span><br><span class="line">        List&lt;User&gt; users_ = <span class="keyword">null</span>;</span><br><span class="line">        userList.add(user);</span><br><span class="line">        userList.addAll(users_);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="Optional-空指针"><a href="#Optional-空指针" class="headerlink" title="Optional 空指针"></a>Optional 空指针</h4><p>代表一个值存在不存在，java8之前用null表示不存在，可以看作至多包含一个元素的集合</p>
<ul>
<li>与直接判断是否为null无区别</li>
<li>认识到 orElse 、get 的妙用</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OptionalUsage</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> name;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">isUserEqualNull</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (user != <span class="keyword">null</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">"User is not null"</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.out.println(<span class="string">"User is null"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        Optional&lt;User&gt; optional = Optional.empty();</span><br><span class="line">        <span class="keyword">if</span> (optional.isPresent()) &#123;</span><br><span class="line">            System.out.println(<span class="string">"User is not null"</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.out.println(<span class="string">"User is null"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> User <span class="title">anoymos</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> User();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 没有意义的使用方法</span></span><br><span class="line">        isUserEqualNull();</span><br><span class="line"></span><br><span class="line">        User user = <span class="keyword">null</span>;</span><br><span class="line">        Optional&lt;User&gt; optionalUser = Optional.ofNullable(<span class="keyword">null</span>);</span><br><span class="line">        <span class="comment">// 存在及返回</span></span><br><span class="line">        optionalUser.orElse(<span class="keyword">new</span> User());</span><br><span class="line">        <span class="comment">// 存在则返回 空则由函数产生新的对象，复用性更强</span></span><br><span class="line">        optionalUser.orElseGet(() -&gt; anoymos());</span><br><span class="line">        <span class="comment">// 存在即返回 否则抛出异常</span></span><br><span class="line">        optionalUser.orElseThrow(RuntimeException::<span class="keyword">new</span>);</span><br><span class="line">        <span class="comment">// 存在才去做相应的处理</span></span><br><span class="line">        optionalUser.ifPresent(u-&gt; System.out.println(u.getName()));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// map 可以对Optional中的对象执行某种操作 且会返回一个 Optional对象</span></span><br><span class="line">        optionalUser.map(u-&gt;u.getName()).orElse(<span class="string">"anymos"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// map 可以无限级联操作</span></span><br><span class="line">        optionalUser.map(u-&gt;u.getName()).map(name-&gt;name.length()).orElse(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="try-catch没有解决问题"><a href="#try-catch没有解决问题" class="headerlink" title="try-catch没有解决问题"></a>try-catch没有解决问题</h4><p>exception 意外、例外。</p>
<ul>
<li>使用异常，而不是返回码（或类似），因为异常会更加详细</li>
<li>主动捕获检查性异常，并对异常信息进行返回</li>
<li>保持代码整洁，一个方法不要有多个 try catch 或者嵌套的 try catch</li>
<li>捕获更加具体的异常，而不是通用的 Exception</li>
<li>合理的设计自定义的异常类</li>
</ul>
<h4 id="编码中常见的异常"><a href="#编码中常见的异常" class="headerlink" title="编码中常见的异常"></a>编码中常见的异常</h4><h3 id="数值计算"><a href="#数值计算" class="headerlink" title="数值计算"></a>数值计算</h3><h4 id="BigDecimal"><a href="#BigDecimal" class="headerlink" title="BigDecimal"></a>BigDecimal</h4><p>精确计算的类，核心是精度，精度如果不匹配，结果大概率不会符合预期</p>
<ul>
<li>初始化设置精度</li>
<li>除法除不尽设置精度</li>
<li>比较用compare </li>
</ul>
<h4 id="SimpleDateFormat-常用的坑"><a href="#SimpleDateFormat-常用的坑" class="headerlink" title="SimpleDateFormat 常用的坑"></a>SimpleDateFormat 常用的坑</h4><ul>
<li>可以解析大于/等于它时间精度的日期</li>
<li>线程不安全<ul>
<li>定义为局部变量</li>
<li>使用 ThreadLocal</li>
<li>使用 synchronize 不推荐</li>
</ul>
</li>
</ul>
<h4 id="for循环"><a href="#for循环" class="headerlink" title="for循环"></a>for循环</h4><ul>
<li>如果是数组，有多余的索引</li>
<li>for-each 优于 for，任何实现 Iterable 接口的对象都可以使用</li>
</ul>
<h4 id="不好好判等，集合存储就会乱套"><a href="#不好好判等，集合存储就会乱套" class="headerlink" title="不好好判等，集合存储就会乱套"></a>不好好判等，集合存储就会乱套</h4><ul>
<li>Object 的 equals 和 hashcode 方法<ul>
<li>默认的 equals 对象地址，hashcode 根据对象地址生成一个整数值</li>
<li>只重写 equals 方法的问题</li>
</ul>
</li>
<li>集合中的元素的索引竟然也与 equals 方法相关<ul>
<li>类实现了compareTo 方法 就需要实现equals</li>
<li>compareTo 与 equals 实现过程需要一致</li>
</ul>
</li>
</ul>
<h4 id="使用lombok-注解没有达到预期"><a href="#使用lombok-注解没有达到预期" class="headerlink" title="使用lombok 注解没有达到预期"></a>使用lombok 注解没有达到预期</h4><ul>
<li><p>常用注解</p>
<ul>
<li>@Getter @Setter</li>
<li>@ToString</li>
<li>@Data<ul>
<li>setter getter equals canEqual hashCode toString</li>
</ul>
</li>
<li>@NoArgsContructor</li>
<li>@Sl4j</li>
</ul>
</li>
<li><p>Source.java  抽象语法树（AST） Target.ava </p>
</li>
<li><p>单字母的小写第二个字母大写会转成一个单词，编写代码不符合规范</p>
</li>
</ul>
<h4 id="避免抽象类和接口的选择失误"><a href="#避免抽象类和接口的选择失误" class="headerlink" title="避免抽象类和接口的选择失误"></a>避免抽象类和接口的选择失误</h4><ul>
<li><p>设计 Worker</p>
<ul>
<li>工作、行为拆分为抽象类合适吗？不合适</li>
<li>工作、行为拆分为接口合理吗？不合理</li>
</ul>
</li>
<li><p>抽象类、接口的含义和特性</p>
<ul>
<li>抽象类是子类的通用特性，包含属性和行为；接口是定义行为，并不关心谁去实现</li>
<li>抽象类是对类本质的抽象，表达的是is-a的关系；接口是对行为的抽象，表达的是 like a 的关系</li>
</ul>
</li>
<li><p>抽象类、接口的相同点</p>
</li>
</ul>
<h4 id="函数式接口和lambda表达式"><a href="#函数式接口和lambda表达式" class="headerlink" title="函数式接口和lambda表达式"></a>函数式接口和lambda表达式</h4><ul>
<li><p>匿名内部类使用lambda表达式代替</p>
<ul>
<li>@FunctionInterface 有且只有一个抽象类接口</li>
</ul>
</li>
<li><p>不熟悉中间操作和结束操作引发的语法错误</p>
</li>
</ul>
<h3 id="反射、泛型"><a href="#反射、泛型" class="headerlink" title="反射、泛型"></a>反射、泛型</h3><h4 id="实现了-Serializable-接口却报错"><a href="#实现了-Serializable-接口却报错" class="headerlink" title="实现了 Serializable 接口却报错"></a>实现了 Serializable 接口却报错</h4><ul>
<li>子类实现了序列化接口，父类没实现，子类可以序列化，父类必须有无参构造函数</li>
<li>类中存在引用对象，那么，这个类对象必须都是可序列化的</li>
<li>同一个对象多次序列化（之间有属性更新），会影响结果吗</li>
</ul>
<h4 id="泛型不仅仅是规定集合中类型"><a href="#泛型不仅仅是规定集合中类型" class="headerlink" title="泛型不仅仅是规定集合中类型"></a>泛型不仅仅是规定集合中类型</h4><ul>
<li><p>泛型就是参数化类型，将类型原来的具体类型参数化</p>
</li>
<li><p>能够不创建新类型的情况下，通过泛型指定不同类型控制形参</p>
</li>
<li><p>特性</p>
<ul>
<li><p>先检查再编译</p>
</li>
<li><p>不支持继承</p>
</li>
<li><p>不能是基本类型</p>
</li>
<li><p>泛型方法参数只能类类型，不能是简单类型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">doSomething</span><span class="params">(T... values)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (T value : values) &#123;</span><br><span class="line">        System.out.println(value);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">    Integer[] ints1 = <span class="keyword">new</span> Integer[]&#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>&#125;;</span><br><span class="line">    <span class="keyword">int</span>[] ints2 = <span class="keyword">new</span> <span class="keyword">int</span>[] &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,&#125;;</span><br><span class="line"></span><br><span class="line">    doSomething(ints1);</span><br><span class="line">    System.out.println(<span class="string">"------------------------------"</span>);</span><br><span class="line">    doSomething(ints2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
</li>
</ul>
<h4 id="切记不要使用原始类型"><a href="#切记不要使用原始类型" class="headerlink" title="切记不要使用原始类型"></a>切记不要使用原始类型</h4><ul>
<li>初步优化，指定 <code>List&lt;Object&gt;</code>，明确告诉编译器可以存储任意对象</li>
</ul>
<h4 id="反射"><a href="#反射" class="headerlink" title="反射"></a>反射</h4><ul>
<li><p>允许运行中 java 获取自身信息，并可以操作类或对象的内部属性</p>
</li>
<li><p>应用场景</p>
<ul>
<li>开发通用框架，动态加载需要的对象</li>
<li>动态代理</li>
<li>注解</li>
<li>可扩展性功能</li>
</ul>
</li>
<li><p>缺陷</p>
<ul>
<li>性能开销</li>
<li>破坏封装性</li>
<li>内部曝光</li>
</ul>
</li>
<li><p>类加载过程</p>
<ul>
<li>编译 java文件 - java编译器 - Class 文件</li>
<li>加载与运行 JVM 类加载器、执行引擎</li>
</ul>
</li>
<li><p>Method类</p>
<ul>
<li>getMethod</li>
<li>getDeclaredMethod</li>
<li>getMethods</li>
<li>getDeclaredMethods</li>
</ul>
</li>
<li><p>什么场景获取不到Method</p>
<ul>
<li><p>方法定义基本类型参数，获取方法也必须指定基本类型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">numeric</span><span class="params">(<span class="keyword">int</span> age)</span> </span>&#123;</span><br><span class="line">    return Boss.class.getName() + ": " + age;</span><br><span class="line">&#125;</span><br><span class="line">Method numeric = clz.getMethod(<span class="string">"numeric"</span>, <span class="keyword">int</span><span class="class">.<span class="keyword">class</span>)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>getDeclaredMethod 不能从当前类获取到父类的方法</p>
</li>
</ul>
</li>
</ul>
<h4 id="并不是所有字符串拼接都用-StringBuilder"><a href="#并不是所有字符串拼接都用-StringBuilder" class="headerlink" title="并不是所有字符串拼接都用 StringBuilder"></a>并不是所有字符串拼接都用 StringBuilder</h4><ul>
<li><p>使用 <code>+</code> 去拼接字符串，会造成怎样的性能损失</p>
<ul>
<li>空间浪费 每次拼接都会创建新对象</li>
<li>时间浪费，产生大量临时对象，影响 young gc 甚至 full gc</li>
<li><code>javac StringContact.java</code></li>
<li><code>javap -l -c -p .\StringContact.class</code></li>
</ul>
</li>
<li><p>StringBuffer 和 StringBuilder 三个区别</p>
<ul>
<li>线程安全</li>
<li>缓冲区 StringBuffer 使用了缓冲区（toString方法）</li>
<li>性能 StringBuilder 性能远大于 StringBuffer</li>
</ul>
</li>
</ul>
<h4 id="分不清深浅拷贝"><a href="#分不清深浅拷贝" class="headerlink" title="分不清深浅拷贝"></a>分不清深浅拷贝</h4><ul>
<li>浅拷贝，属性是引用类型的情况是同一个引用对象</li>
<li>深拷贝，属性是引用类型的情况是不同引用对象</li>
<li>Cloneable接口<ul>
<li>标记接口，同clone方法是不同的</li>
<li>如果类没有实现 Cloneable接口，调用clone方法会报错</li>
<li>Object 提供的clone方法是浅拷贝</li>
</ul>
</li>
</ul>
<h3 id="线程安全"><a href="#线程安全" class="headerlink" title="线程安全"></a>线程安全</h3><h4 id="用不好-Synchronized-关键字"><a href="#用不好-Synchronized-关键字" class="headerlink" title="用不好 Synchronized 关键字"></a>用不好 Synchronized 关键字</h4><ul>
<li><p>多线程操作变量的过程</p>
</li>
<li><p>synchronized 方法并不会被继承，需要在子类中重写指定</p>
</li>
<li><p>标注在哪里</p>
<ul>
<li>方法声明，非静态方法（对象锁）、静态方法（类对象锁，类锁）</li>
<li>方法体</li>
</ul>
</li>
<li><p>怎么实现的</p>
<ul>
<li>monitor enter 和 monitor exit</li>
</ul>
</li>
<li><p>JDK优化</p>
<ul>
<li>偏向锁</li>
<li>轻量级锁（自旋）</li>
<li>重量级锁</li>
</ul>
</li>
</ul>
<h4 id="多线程下如何更新值"><a href="#多线程下如何更新值" class="headerlink" title="多线程下如何更新值"></a>多线程下如何更新值</h4><ul>
<li>多线程下  i++ 大概率会得到不符合预期的结果<ul>
<li>取数、累加、存储，不是原子性</li>
<li>常用的原子类，AtomicInteger ，CAS操作；悲观锁，互斥同步（同一时刻有且只有一个线程操作数据）；乐观锁，非阻塞同步锁，cas实现，需要解决 <strong>aba</strong> 问题（内部维护modCount只增不减，大多数aba问题不会产生）</li>
</ul>
</li>
</ul>
<h4 id="提到阻塞队列，是不是很懵"><a href="#提到阻塞队列，是不是很懵" class="headerlink" title="提到阻塞队列，是不是很懵"></a>提到阻塞队列，是不是很懵</h4><ul>
<li><p>关于阻塞队列</p>
<ul>
<li><p>核心定义：支持两个附加操作的队列，队列空则等；队列满则等</p>
</li>
<li><p>四种处理方法，生产者和消费者的过程</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>抛出异常</th>
<th>返回特殊值</th>
<th>一直阻塞</th>
<th>超时退出</th>
</tr>
</thead>
<tbody><tr>
<td>插入</td>
<td>add</td>
<td>offer</td>
<td>put</td>
<td>offer(time)</td>
</tr>
<tr>
<td>移除</td>
<td>remove</td>
<td>poll</td>
<td>take</td>
<td>poll(time)</td>
</tr>
<tr>
<td>检查</td>
<td>element</td>
<td>pee</td>
<td>-</td>
<td>-</td>
</tr>
</tbody></table>
</li>
</ul>
</li>
</ul>
<h4 id="并不是什么时候都适合用Copy-On-Write"><a href="#并不是什么时候都适合用Copy-On-Write" class="headerlink" title="并不是什么时候都适合用Copy-On-Write"></a>并不是什么时候都适合用Copy-On-Write</h4><ul>
<li><p>并发对同一个集合进行读取会抛出异常</p>
<ul>
<li>ConcurrentModificationExpcetion</li>
</ul>
</li>
<li><p>使用 CopyOnWrite 容器解决并发读写问题</p>
<ul>
<li>是一种优化策略，是一种延时懒惰策略，是对读写分离（不同的容器）思想的实现</li>
<li>jdk17 add 切换成 synchronized 锁 ；之前是 Reentlock</li>
<li>优点：并发读不需要加锁，提高了程序并发度</li>
<li>缺点：内存占用问题、一致性问题</li>
<li>应用场景：适合读（不加锁）多写少的并发场景，例如：白名单、黑名单</li>
<li>注意：减少扩容开销、使用批量添加</li>
</ul>
</li>
<li><p>对比 Collections.synchronizedList</p>
<ul>
<li>都可以实现线程安全的集合</li>
<li>CopyOnWrite 写操作不仅要枷锁，而且对内部数组进行了 copy 写性能更差</li>
<li>CopyOnWrite 直接读，读性能高</li>
</ul>
</li>
</ul>
<h4 id="用不好-ThreadLocal-极有可能出现内存泄漏"><a href="#用不好-ThreadLocal-极有可能出现内存泄漏" class="headerlink" title="用不好 ThreadLocal 极有可能出现内存泄漏"></a>用不好 ThreadLocal 极有可能出现内存泄漏</h4><ul>
<li>不恰当理解<ul>
<li>用途是解决多线程并发（同步）问题</li>
<li>为了解决多线程访问资源时共享问题</li>
</ul>
</li>
<li>基本原理<ul>
<li>同一个ThreadLocal所包含的对象，在不同的 Thread 中有不同的副本（每个线程需要自己独立的实例且该实例需要在多个方法中使用）</li>
</ul>
</li>
<li>使用误区<ul>
<li>不支持继承，父子线程</li>
<li><strong>遇到线程池，如果不及时清理现场，会造成数据混乱</strong></li>
</ul>
</li>
<li>实现方式<ul>
<li>维护线程与实例的映射 ThreadLocal 维护MAP 需要锁</li>
<li><strong>线程中有MAP维护 ThreadLocal与实例的映射，存在内存泄漏</strong></li>
</ul>
</li>
</ul>
<h3 id="Spring中常见的坑"><a href="#Spring中常见的坑" class="headerlink" title="Spring中常见的坑"></a>Spring中常见的坑</h3><h4 id="默认bean名称造成空指针"><a href="#默认bean名称造成空指针" class="headerlink" title="默认bean名称造成空指针"></a>默认bean名称造成空指针</h4><h4 id="不自动注入还会获取上下文吗"><a href="#不自动注入还会获取上下文吗" class="headerlink" title="不自动注入还会获取上下文吗"></a>不自动注入还会获取上下文吗</h4><ul>
<li><p>Spring 核心时容器，但是容器不是唯一</p>
<ul>
<li>不常用的容器实现 BeanFactory</li>
<li>高级实现，继承 BeanFactory 派生的应用上下文 ApplicationContext</li>
</ul>
</li>
<li><p>获取应用上下文四种方式</p>
<ul>
<li>ApplicationContextInitizer<ul>
<li>Use Initializer</li>
</ul>
</li>
<li>ApplicationListener</li>
</ul>
</li>
<li><p>多线程 Spring Bean 数据不符合预期</p>
</li>
</ul>
<h3 id="SpringBoot常见的坑"><a href="#SpringBoot常见的坑" class="headerlink" title="SpringBoot常见的坑"></a>SpringBoot常见的坑</h3><h4 id="配置数据总是出错？搞清楚加载顺序"><a href="#配置数据总是出错？搞清楚加载顺序" class="headerlink" title="配置数据总是出错？搞清楚加载顺序"></a>配置数据总是出错？搞清楚加载顺序</h4><p><strong>SpringBoot 配置文件</strong></p>
<ul>
<li>SpringBoot 使用一个全局的配置文件，且配置文件名是固定的。配置文件的作用是用来修改  SpringBoot 自动配置的默认值</li>
<li>可以使用 application.properties 格式 也可以用使用 application.yml 格式</li>
<li>由于 YAML 格式紧凑且可读性高，所以，SpringBoot 支持并推荐使用  YAML 格式的配置文件</li>
<li>如果两种配置文件同时存在的时候，默认优先使用 .properties 配置文件</li>
</ul>
<h3 id="Redis中常见的坑"><a href="#Redis中常见的坑" class="headerlink" title="Redis中常见的坑"></a>Redis中常见的坑</h3><h4 id="怎么选择正确数据类型"><a href="#怎么选择正确数据类型" class="headerlink" title="怎么选择正确数据类型"></a>怎么选择正确数据类型</h4><ul>
<li>几乎所有的数据都可以使用 string 表示<ul>
<li>以用户信息数据为例<ul>
<li>UserInfo id 1 name isssac age 19 gender m 键中包含id</li>
</ul>
</li>
</ul>
</li>
<li>String 类型存储数据弊端<ul>
<li>浪费存储空间，key也是需要存储空间</li>
<li>管理、维护会成为噩梦，Redis 中存在大量的 KV 对象</li>
<li>key 冲突的几率变高（不同的业务系统共用一个 Redis 服务）</li>
<li>用map存储 user_1 {id:1, name: issac}</li>
<li>存储json字符串是否可行？<ul>
<li>反序列化操作的效率低下</li>
<li>结合业务场景需求</li>
</ul>
</li>
</ul>
</li>
<li>key 的命名策略（建议）<ul>
<li>同一个 Redis 服务被公司中的各个业务线共用<ul>
<li>业务线名称+工程名+模块名+（有意义的）键名</li>
<li>cbas_recsys_classinfo_item_user_1</li>
</ul>
</li>
</ul>
</li>
<li>常用数据类型及其适用场景<ul>
<li>string 应用最为广泛的数据类型，例如：计数器 session 等键值独立的数据</li>
<li>hash 存储结构化对象，KV共同构成一个对象信息</li>
<li>list 队列、栈、有界队列（控制队列中的个数），</li>
<li>set 去重、无序的数据集合，在类似于社交的业务功能上有广泛应用，例如：共同关注、共同喜好、数据去重</li>
<li>sortedset 带有权重的集合，在类似排行榜业务上有防范应用，且可以实现范围查找</li>
</ul>
</li>
</ul>
<h4 id="使用了事务功能，怎么没回滚"><a href="#使用了事务功能，怎么没回滚" class="headerlink" title="使用了事务功能，怎么没回滚"></a>使用了事务功能，怎么没回滚</h4><ul>
<li><p>Redis事务</p>
<ul>
<li><p>事务基础：四个指令 MULTI EXEC DISCARD WATCH</p>
</li>
<li><p>事务可以一次执行多个命令，并且带有以下两个重要的保证，单独的隔离操作、原子操作</p>
</li>
<li><pre><code class="sh">docker run --restart=always -p 6379:6379 --name myredis -d redis:7.0.12</code></pre>
</li>
<li></li>
</ul>
</li>
</ul>
<h4 id="Redis-性能上不去，可能是有-Big-Key"><a href="#Redis-性能上不去，可能是有-Big-Key" class="headerlink" title="Redis 性能上不去，可能是有 Big Key"></a>Redis 性能上不去，可能是有 Big Key</h4><ul>
<li>数据量大的key，比如字符串 <strong>Value值非常大（大于10KB）</strong>、<strong>哈希、列表、集合、有序集合元素多（元素个数大于 5000）</strong></li>
<li>Big Key 造成的危害<ul>
<li>内存不均、超时阻塞、网络流量阻塞、过期删除、迁移困难</li>
</ul>
</li>
</ul>
<p><strong>怎么产生的（基本上是疏忽、考虑不周全造成）</strong></p>
<ul>
<li>社交类场景：典型的是粉丝列表，对于明显或者大V来说，需要特殊设计，否则，就造成了Big Key</li>
<li>汇总统计类场景：每天都会产生报表数据，报表数据汇总到一个 key，日积月累就成了 BigKey</li>
<li>日常缓存类场景：对DB中的数据进行缓存，大表（存在大字段）很可能会产生 BigKey</li>
</ul>
<p><strong>如何发现 Big Key</strong></p>
<ul>
<li>redis-cli 提供了 –bigkeys 来查找 bigkey ：给出了每种数据结构的 top 1 bigkey</li>
<li>Redis4.0 提供 memory usage 命令可以计算每个键值的字节数（包括键值对和指针一共需要的内存）</li>
</ul>
<p><strong>删除 Big Key 不要贸然行动</strong></p>
<ul>
<li>string 可以直接使用del，不会产生阻塞</li>
<li>dict 使用hscan 命令每次获取部分 field-value ，再使用hdel 删除每个field</li>
<li>list 使用 ltrim 命令渐进式删除列表元素，直到把列表删除</li>
<li>set 使用 sscan 命令，每次获取部分元素，再使用 srem 命令删除每个元素</li>
<li>sortedset 使用 zcan 命令，每次获取部分元素，再使用 zremrangebyrank 命令删除元素</li>
</ul>
<h4 id="Redis-怎么出现内存耗尽"><a href="#Redis-怎么出现内存耗尽" class="headerlink" title="Redis 怎么出现内存耗尽"></a>Redis 怎么出现内存耗尽</h4><ul>
<li>业务不断发展，缓存数据不断增多，需要消耗 Redis 内存<ul>
<li>不可避免</li>
</ul>
</li>
<li>无效的（过期的）数据没有及时清理，需要消耗 Redis 内存</li>
<li>没有对“冷数据”进行降级，需要消耗 Redis 内存</li>
</ul>
<p><strong>使用 EXPIRE 命令将 KEY 标记为 Volatile 易失的</strong></p>
<ul>
<li>使用 EXPIRE key seconds 命令给 key 设置生存时间</li>
<li>如果一个命令只是修改一个带生存时间的 key 的值而不是用一个新 key 的值来代替它的，那么生存时间不会被改变 rename incr 不会变</li>
<li>persist 可以再不删除key的情况下，移除 key 的生存时间，让key重写成为一个持久的key</li>
<li>可以对一个已经有生存时间的 key 执行 EXPIRE 命令，新指定的生存时间会取代旧的生存时间</li>
</ul>
<p><strong>Redis过期删除策略</strong></p>
<ul>
<li>定时删除，对于个每个设置了过期时间的 key 都会创建一个定时器，一旦达到过期时间就立即删除</li>
<li>惰性删除：当访问一个key，才判断是否过期，过期则删除</li>
<li>定期删除：每隔一段时间，扫描Redis中过期的key字典，并清除过期的key</li>
<li>Redis 同时使用了定期删除 + 惰性删除</li>
</ul>
<h4 id="有了过期机制，内存还是不够用"><a href="#有了过期机制，内存还是不够用" class="headerlink" title="有了过期机制，内存还是不够用"></a>有了过期机制，内存还是不够用</h4><p><strong>为什么不够用</strong></p>
<ul>
<li>业务缓存数据需求量大，占用大量的内存空间</li>
<li>过期 key 虽然有很多，但是不能 及时失效</li>
</ul>
<p><strong>Redis内存淘汰策略</strong></p>
<ul>
<li>内存达到 maxmemory 极限时，使用某种算法来决定清理掉哪些数据</li>
<li>常用内存淘汰机制<ul>
<li>noeviction 读请求可以写请求拒绝</li>
<li>allkeys-lru 最近最久没有被使用</li>
<li>allkeys-random 随机</li>
<li>volatile-lru 最早设置了过期时间的key</li>
<li>volatile-random 随机过期时间的key</li>
<li>volatitle-ttl 剩余的ttl时间，越小越优先</li>
</ul>
</li>
</ul>
<h4 id="如何解决频繁的命令往返造成的性能瓶颈"><a href="#如何解决频繁的命令往返造成的性能瓶颈" class="headerlink" title="如何解决频繁的命令往返造成的性能瓶颈"></a>如何解决频繁的命令往返造成的性能瓶颈</h4><ul>
<li>Redis 客户端和服务端的交互模型<ul>
<li>是一个基于 Request 一个 Response 的<strong>同步</strong>请求服务</li>
<li>数据包往返于两端的时间 RTT</li>
</ul>
</li>
<li>Redis pipeline（流水线） 的交互模型<ul>
<li>client &lt;-&gt; client buffer &lt;-&gt;redis server</li>
<li>减少客户端和服务端连接</li>
<li>使用队列实现</li>
</ul>
</li>
<li>pipeline 与原生批量命令对比<ul>
<li>原生批量命令是原子性，pipeline是非原子性</li>
<li>原生命令一次只能执行一种命令，pipeline 支持批量执行不同命令</li>
<li>原生批量命令是服务端实现</li>
</ul>
</li>
<li>注意事项<ul>
<li>命令个数不能太多，数据量过大</li>
<li>会安装指令缓冲的顺序执行，但是可能会穿插其他客户端发送来的命令，即时序性不能保证</li>
<li>某个指令异常，会继续执行</li>
</ul>
</li>
</ul>
<h4 id="你的代码有没有缓存穿透隐患"><a href="#你的代码有没有缓存穿透隐患" class="headerlink" title="你的代码有没有缓存穿透隐患"></a>你的代码有没有缓存穿透隐患</h4><ul>
<li>查询一个一定不存在的数据，如果规则是从数据库中查不到数据则不写入缓存，这会导致这个不存在的数据每次请求都要到数据库中查询</li>
<li>问题1：系统启动初期已经预置了数，但是并未加载到Redis中，导致前期大量的请求由MYSQL 承担</li>
<li>问题2：可以利用不存在的key的频繁攻击应用，流量大时，可能会使数据库宕机</li>
</ul>
<p>如何解决</p>
<ul>
<li>缓存预热：系统上线后，提前将相关的缓存数据直接加载到缓存系统</li>
<li>如果查询数据库为空，直接设置一个默认值（无意义）存放到缓存，这样第二次到缓存中获取就有值了，则不会继续访问数据库<ul>
<li>设置过期时间</li>
<li>更新数据库时及时更新缓存</li>
</ul>
</li>
<li>在数据处理层，<strong>进行数据校验</strong>，判等数据类型和数据范围</li>
<li><strong>使用布隆过滤器</strong>，把所有可能存在的数据哈希到一个足够大的 bitmap中，一个一定不存在的数据会被 bitmap拦截掉</li>
</ul>
<h4 id="出现缓存雪崩"><a href="#出现缓存雪崩" class="headerlink" title="出现缓存雪崩"></a>出现缓存雪崩</h4><ul>
<li>热点数据集中失效</li>
<li>瞬时请求都会被转发到 MYSQL 给后端数据库造成瞬时压力</li>
</ul>
<p>如何解决</p>
<ul>
<li>过期时间错开（可以在一个基础时间上增减一个随机值），避免热点数据集中失效</li>
<li>本地缓存 （JVM Cache） + Hystrix 限流&amp;降级</li>
</ul>

    </div>

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>
        <div class="reward-container">
  <div>辛苦码字分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.jpg" alt="Issac Young 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpg" alt="Issac Young 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Issac Young
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://issacyoung.cn/2024/04/21/%E4%B8%80%E6%AD%A5%E4%B8%80%E6%AD%A5%E4%B9%8Bjava%E5%B8%B8%E8%A7%81%E5%9D%91/" title="一步一步之java常见坑">http://issacyoung.cn/2024/04/21/一步一步之java常见坑/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

            <div class="social-item">
              <a target="_blank" class="social-link" href="/atom.xml">
                <span class="icon">
                  <i class="fa fa-rss"></i>
                </span>

                <span class="label">RSS</span>
              </a>
            </div>
    </div>
  </div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2024/03/07/%E4%B8%80%E6%AD%A5%E4%B8%80%E6%AD%A5%E4%B9%8BPyTorch/" rel="prev" title="一步一步之PyTorch">
      <i class="fa fa-chevron-left"></i> 一步一步之PyTorch
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#空指针如何避免"><span class="nav-number">1.</span> <span class="nav-text">空指针如何避免</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#赋值时自动拆箱出现空指针"><span class="nav-number">1.1.</span> <span class="nav-text">赋值时自动拆箱出现空指针</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#建议"><span class="nav-number">1.1.1.</span> <span class="nav-text">建议</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串、数组、集合-N-P-E"><span class="nav-number">1.2.</span> <span class="nav-text">字符串、数组、集合 N P E</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Optional-空指针"><span class="nav-number">1.3.</span> <span class="nav-text">Optional 空指针</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#try-catch没有解决问题"><span class="nav-number">1.4.</span> <span class="nav-text">try-catch没有解决问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#编码中常见的异常"><span class="nav-number">1.5.</span> <span class="nav-text">编码中常见的异常</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数值计算"><span class="nav-number">2.</span> <span class="nav-text">数值计算</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#BigDecimal"><span class="nav-number">2.1.</span> <span class="nav-text">BigDecimal</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#SimpleDateFormat-常用的坑"><span class="nav-number">2.2.</span> <span class="nav-text">SimpleDateFormat 常用的坑</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#for循环"><span class="nav-number">2.3.</span> <span class="nav-text">for循环</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#不好好判等，集合存储就会乱套"><span class="nav-number">2.4.</span> <span class="nav-text">不好好判等，集合存储就会乱套</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用lombok-注解没有达到预期"><span class="nav-number">2.5.</span> <span class="nav-text">使用lombok 注解没有达到预期</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#避免抽象类和接口的选择失误"><span class="nav-number">2.6.</span> <span class="nav-text">避免抽象类和接口的选择失误</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#函数式接口和lambda表达式"><span class="nav-number">2.7.</span> <span class="nav-text">函数式接口和lambda表达式</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#反射、泛型"><span class="nav-number">3.</span> <span class="nav-text">反射、泛型</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实现了-Serializable-接口却报错"><span class="nav-number">3.1.</span> <span class="nav-text">实现了 Serializable 接口却报错</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#泛型不仅仅是规定集合中类型"><span class="nav-number">3.2.</span> <span class="nav-text">泛型不仅仅是规定集合中类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#切记不要使用原始类型"><span class="nav-number">3.3.</span> <span class="nav-text">切记不要使用原始类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#反射"><span class="nav-number">3.4.</span> <span class="nav-text">反射</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#并不是所有字符串拼接都用-StringBuilder"><span class="nav-number">3.5.</span> <span class="nav-text">并不是所有字符串拼接都用 StringBuilder</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分不清深浅拷贝"><span class="nav-number">3.6.</span> <span class="nav-text">分不清深浅拷贝</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程安全"><span class="nav-number">4.</span> <span class="nav-text">线程安全</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#用不好-Synchronized-关键字"><span class="nav-number">4.1.</span> <span class="nav-text">用不好 Synchronized 关键字</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多线程下如何更新值"><span class="nav-number">4.2.</span> <span class="nav-text">多线程下如何更新值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#提到阻塞队列，是不是很懵"><span class="nav-number">4.3.</span> <span class="nav-text">提到阻塞队列，是不是很懵</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#并不是什么时候都适合用Copy-On-Write"><span class="nav-number">4.4.</span> <span class="nav-text">并不是什么时候都适合用Copy-On-Write</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#用不好-ThreadLocal-极有可能出现内存泄漏"><span class="nav-number">4.5.</span> <span class="nav-text">用不好 ThreadLocal 极有可能出现内存泄漏</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Spring中常见的坑"><span class="nav-number">5.</span> <span class="nav-text">Spring中常见的坑</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#默认bean名称造成空指针"><span class="nav-number">5.1.</span> <span class="nav-text">默认bean名称造成空指针</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#不自动注入还会获取上下文吗"><span class="nav-number">5.2.</span> <span class="nav-text">不自动注入还会获取上下文吗</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SpringBoot常见的坑"><span class="nav-number">6.</span> <span class="nav-text">SpringBoot常见的坑</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#配置数据总是出错？搞清楚加载顺序"><span class="nav-number">6.1.</span> <span class="nav-text">配置数据总是出错？搞清楚加载顺序</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Redis中常见的坑"><span class="nav-number">7.</span> <span class="nav-text">Redis中常见的坑</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#怎么选择正确数据类型"><span class="nav-number">7.1.</span> <span class="nav-text">怎么选择正确数据类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用了事务功能，怎么没回滚"><span class="nav-number">7.2.</span> <span class="nav-text">使用了事务功能，怎么没回滚</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis-性能上不去，可能是有-Big-Key"><span class="nav-number">7.3.</span> <span class="nav-text">Redis 性能上不去，可能是有 Big Key</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis-怎么出现内存耗尽"><span class="nav-number">7.4.</span> <span class="nav-text">Redis 怎么出现内存耗尽</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#有了过期机制，内存还是不够用"><span class="nav-number">7.5.</span> <span class="nav-text">有了过期机制，内存还是不够用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#如何解决频繁的命令往返造成的性能瓶颈"><span class="nav-number">7.6.</span> <span class="nav-text">如何解决频繁的命令往返造成的性能瓶颈</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#你的代码有没有缓存穿透隐患"><span class="nav-number">7.7.</span> <span class="nav-text">你的代码有没有缓存穿透隐患</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#出现缓存雪崩"><span class="nav-number">7.8.</span> <span class="nav-text">出现缓存雪崩</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Issac Young"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Issac Young</p>
  <div class="site-description" itemprop="description">现代生活工作节奏越来越快，需要有时间和空间沉淀积累，将知识点规划成树，记录自己的感悟心得。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">26</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/IssacYoung2013" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;IssacYoung2013" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:issacyoung@msn.cn" title="E-Mail → mailto:issacyoung@msn.cn" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Issac Young</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">64k</span>
</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/clicklove.js"></script>

